package com.bm.connect.service;

import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ChatService  implements IchatService {

    //创建一个线程安全的集合，用于存储所有已连接的 WebSocket 客户端会话
    private final Set<WebSocketSession> sessions = ConcurrentHashMap.newKeySet();
    // 存储会话ID和对应的用户名
    private final Map<String, String> sessionUsernameMap = new ConcurrentHashMap<>();

    @Override
    public void addSession(WebSocketSession session, String username) {
        sessions.add(session); // 新连接加入集合
        sessionUsernameMap.put(session.getId(), username); // 存储会话ID和用户名
    }

    @Override
    public void removeSession(WebSocketSession session) {
        sessions.remove(session);// 连接关闭时移除
        sessionUsernameMap.remove(session.getId()); // 移除会话ID和用户名映射
    }

    @Override
    //sender：1.表示发送消息的客户端会话（WebSocketSession）。
    // 2.标识消息的来源。
    public void broadcastMessage(WebSocketSession sender, String message) {
        // 广播消息给所有客户端
        for (WebSocketSession session : sessions) {
            if (session != sender && session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String getUsername(String sessionId) {
        return sessionUsernameMap.get(sessionId);
    }

    @Override
    public void sendPrivateMessage(WebSocketSession sender, String receiverUsername, String message) throws IOException {
        // 查找接收者的会话并发送私聊消息
        for (Map.Entry<String, String> entry : sessionUsernameMap.entrySet()) {
            if (entry.getValue().equals(receiverUsername)) {
                WebSocketSession receiverSession = sessions.stream()
                        .filter(s -> s.getId().equals(entry.getKey()))
                        .findFirst()
                        .orElse(null);
                if (receiverSession != null && receiverSession.isOpen()) {
                    receiverSession.sendMessage(new TextMessage(message));
                    break; // 找到接收者后退出循环
                }
            }
        }
    }
}